<?php
/**
 * 微信退款接口
 * User: 梁晓伟  lxw11109@gmail.com
 * Date: 2017-09-07
 * Time: 17:44
 */

namespace App\Libs\Contracts\PayMent\Wxpay;


use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\OrderRefund;
use App\Services\Front\UserScoreService;

class Refund
{
    /**
     *
     * @param $refund
     * @return bool
     * @throws \Exception
     */
    public function refund($refund)
    {
		
        $url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
        $model = new WxPayApi();
        $data['appid'] = env('APPID');
        $data['mch_id'] = env('MCHID');
        $data['nonce_str'] = nonceStr(32);
        $data['sign_type'] = "MD5";
        $data['out_trade_no'] = $refund['orderNo'];
        $data['out_refund_no'] = $refund['refundNo'];
        $data['total_fee'] = $refund['totalPrice'];
        $data['refund_fee'] = $refund['refundPrice'];
        $data['sign'] = $model->MakeSign($data);
        $xml = $model->ToXml($data);

        $response = $model->postXmlCurl($xml, $url, true);
        $arr = xmlToArray($response);
        dd($arr);
       if($arr['return_code'] === 'FAIL'){
           throw new \Exception("退款失败错误码:".$arr['return_msg']);
       }
	  
        if($arr['result_code'] === "SUCCESS"){
//            $order = Order::where('orderNo',$refund['orderNo'])->first();
//            $refund = OrderRefund::where('refundNo',$refund['refundNo'])->first();
//            $detail = OrderDetail::where('detailId',$refund['orderDetailId'])->first();
//            UserScoreService::decrementYangbeiByOrder($refund['orderNo'],$order['userId'],$detail['totalPrice']);
//            UserScoreService::decrementScore($refund['orderNo'],$order['userId'],$detail['totalPrice']);
            return true;
        }else{
            \Log::error("退款失败错误码:".$arr['err_code_des']);
            return  false;
        }
    }
}